<%@ page language="java" pageEncoding="UTF-8" %>
<%@ page contentType="text/html;charset=UTF-8" import="controller.Constant" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta charste="utf-8">
    <title>聊天室</title>
    <script>
        var ws = new WebSocket("ws://<%=((ServletContext)pageContext.getServletContext()).getInitParameter(Constant.SERVERIPANDPORT)%>/chattingRoom");
        ws.onopen = function () {
            console.log("websocket::open")
        };
        //获得消息
        ws.onmessage = function (message) {
            console.log("websocket::onmessage");
            document.getElementById("content").textContent += message.data + "\n";
        };

        //发送消息
        function postToServer() {
            var value = document.getElementById("msg").value;
            var message = "{\"message\":\"" + value + "\"}";
            ws.send(message);
            document.getElementById("msg").value = "";
        }

        //关闭会话
        function closeConnect() {
            ws.close();
        }

        //窗口关闭时自动关闭连接
        window.onbeforeunload = function () {
            closeConnect();
        }

        //正在关闭的回调方法
        ws.onclose = function () {
            console.log("WebSocket连接关闭");
        }

        //连接错误的方法
        ws.onerror = function () {
            console.log("WebSocket连接发生错误");
        };

    </script>
</head>
<body>
<textarea id="content" readonly></textarea><br/>
<input id="msg" type="text"/>
<button type="submit" id="sendButton" onClick="postToServer()">Send!</button>
<button type="submit" id="sendButton" onClick="closeConnect()">End</button>
</body>

